/**
 * 处理书本接口的业务逻辑
 */
const getRandomInt = require('../utils')
const { createBorrowingRecord, updateBorrowingRecord, getBorrowingList } = require('../service/borrow')
const { getBookInfo, updateBook } = require('../service/book')

class BorrowController {
  // 新增书本借阅记录（借书）
  async borrowBook(ctx, next) {
    // 获取数据
    const { user_id, book_id, borrowing_date } = ctx.request.body
    const borrowing_id = getRandomInt(1, 10000000)
    if (!book_id) {
      ctx.body = {
        code: 400,
        msg: '图书编号不能为空'
      }
      return
    }

    try {
      const temp = await getBookInfo({ book_id })
      if (temp[0].status === '借出') {
        ctx.body = {
          code: 400,
          msg: '该书本已被借出'
        }
        return
      }

      const res = await createBorrowingRecord(borrowing_id, user_id, book_id, borrowing_date)
      ctx.body = {
        code: 200,
        msg: '借阅成功',
        data: res
      }
      updateBook(book_id, null, null, null, null, '借出')
    }
    catch (error) {
      console.error(error);
      ctx.body = {
        code: 500,
        msg: '借阅失败',
        error: error.message
      };
    }
  }

  // 更新书本借阅记录（还书）
  async returnBook(ctx, next) {
    const { borrowing_id, book_id, return_date } = ctx.request.body
    try {
      const temp = await getBookInfo({ book_id })
      if (temp[0].status === '在库') {
        ctx.body = {
          code: 400,
          msg: '该书本已在库'
        }
        return
      }

      const res = await updateBorrowingRecord(borrowing_id, return_date)
      ctx.body = {
        code: 200,
        msg: '归还成功',
        data: res
      }
      updateBook(book_id, null, null, null, null, '在库')
    }
    catch (error) {
      console.error(error);
      ctx.body = {
        code: 500,
        msg: '归还失败',
        error: error.message
      };
    }
  }

  // 获取书本借阅记录列表
  async getBorrowList(ctx, next) {
    try {
      const res = await getBorrowingList()
      ctx.body = {
        code: 200,
        msg: '获取书本借阅记录列表成功',
        data: res
      }
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: '获取书本借阅记录列表失败',
        error: error.message
      };
    }
  }

}

module.exports = new BorrowController()
